<?php
namespace Api;

use C\L\Controller;
use C\P\AliyunOSS;

class ApiController extends Controller
{

    


    function demoAction(){
        $this->success(['error'=>0,'msg'=>'demo']);
    }
  /**
   * Login Action
   **/
    public function loginAction()
    {
        $username = $this->getValue('username', true);
        $password = $this->getValue('password', true);

        $this->s_sysuser->login($username, $password)
        ? $this->success()
        : $this->error();
    }

  /**
   * Logout Action
   **/
    public function logoutAction()
    {
        $this->ssid->destory();
        $this->success();
    }

  /**
   * Config Action
   * return ssid to user
   **/
    public function configAction()
    {
        $this->success([
        'ssid'             => $this->ssid->register(),
        'ssid_expire_time' => $this->ssid->get('expire_time'),
        'is_maintain'      => $this->cache->get('web_is_maintain') ?? false,
        'error'            => $this->config->get('error')->toArray(),
        ]);
    }

  /**
   * Upload Action
   **/
    public function uploadAction()
    {
        if (!$this->request->hasFiles()) {
            return $this->error('无上传文件');
        }

        $files = $this->request->getUploadedFiles();
        $file = $files[0];

        $config = $this->config->get('oss');
        if (!$config) {
            return $this->error('未配置 OSS');
        }

        $driver = new AliyunOSS(
            $config['access_key_id'],
            $config['access_key_secret'],
            $config['endpoint']
        );

        $fileExtension = $file->getExtension();
        $fileName = strtolower(
            date('YmdHis') .  '_' .  uniqid(null) .  '.' .  $fileExtension
        );

        $filePath = $file->getTempName();

        try {
            $response = $driver->upload(
                $config['bucket'],
                $fileName,
                $filePath
            );

            $data = [
            'file' => $response['info']['url'],
            ];

            return $this->success($data);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }
}
